from rest_framework import serializers
from .models import MemberLevel, MemberPoints
from apps.user.models import User

class MemberLevelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MemberLevel
        fields = ['id', 'name', 'points_required', 'discount']

class MemberPointsSerializer(serializers.ModelSerializer):
    level_name = serializers.CharField(source='level.name', read_only=True)
    
    class Meta:
        model = MemberPoints
        fields = ['id', 'user', 'points', 'level', 'level_name']
        read_only_fields = ['points']

class MemberProfileSerializer(serializers.ModelSerializer):
    points = serializers.SerializerMethodField()
    level = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ['id', 'phone', 'avatar', 'points', 'level']
        read_only_fields = ['points', 'level']
    
    def get_points(self, obj):
        try:
            member_points = obj.memberpoints
            return member_points.points
        except MemberPoints.DoesNotExist:
            return 0
    
    def get_level(self, obj):
        try:
            member_points = obj.memberpoints
            if member_points.level:
                return {
                    'id': member_points.level.id,
                    'name': member_points.level.name,
                    'discount': member_points.level.discount
                }
        except MemberPoints.DoesNotExist:
            pass
        return None 